import 'dart:async';
import 'dart:io';

import 'package:app_links/app_links.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:ecy_app_flutter/constant/EcyEventConsnt.dart';
import 'package:ecy_app_flutter/ecycommon/EcyEventBus.dart';
import 'package:ecy_app_flutter/ecycommon/RoutesGlobalKey.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyLogger.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyQQUtil.dart';
import 'package:ecy_app_flutter/user/model/EcyUserModel.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easy_permission/flutter_easy_permission.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

import 'EcyRouter.dart';
import 'package:jpush_flutter/jpush_flutter.dart';

import 'ecycommon/Config.dart';
import 'ecycommon/EcyPermission.dart';
import 'ecycommon/EcyRequestBaseManager.dart';
import 'ecycommon/utils/EcyStorage.dart';
import 'ecycommon/utils/EcyUserUtil.dart';
import 'ecycommon/utils/EcyWxUtil.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  gAppLinks = AppLinks();
  FlutterError.onError = (FlutterErrorDetails details) {
    reportError(details.exception, details.stack);
  };

  await EcyStorage.setString(EcyEventConst.kOnColdStart, "1");

  // 初始化平台通道
  const MethodChannel channel = MethodChannel('com.ecy.app/startup');

  runZonedGuarded(() async {
    // 设置系统UI模式为全屏
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      // 设置状态栏颜色为透明
      statusBarIconBrightness: Brightness.dark,
      // 设置状态栏图标亮度
      systemNavigationBarColor: Colors.transparent,
      // 设置导航栏颜色为透明
      systemNavigationBarIconBrightness: Brightness.dark,
      // 设置导航栏图标亮度
      systemNavigationBarDividerColor: Colors.transparent, // 设置导航栏分隔线颜色为透明
    ));
    // WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
    // FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
    // whenever your initialization is completed, remove the splash screen:
    // FlutterNativeSplash.remove();
    runApp(MyApp(gnavigatorKey: RoutesGlobalKey.navigatorKey));
  }, (Object e, StackTrace strace) {
    reportError(e, strace);
  });
}

late AppLinks gAppLinks;

Future<void> reportError(dynamic error, dynamic stackTrace) async {
  EcyUserModel? userModel = await EcyUserUtil.getLoginedUserInfo();
  // 获取设备信息
  Map<String, dynamic> info = <String, dynamic>{};
  final deviceInfo = DeviceInfoPlugin();
  if (Platform.isAndroid) {
    // Android 设备
    AndroidDeviceInfo build = await deviceInfo.androidInfo;
    info = <String, dynamic>{
      'version.securityPatch': build.version.securityPatch,
      'version.sdkInt': build.version.sdkInt,
      'version.release': build.version.release,
      'version.previewSdkInt': build.version.previewSdkInt,
      'version.incremental': build.version.incremental,
      'version.codename': build.version.codename,
      'version.baseOS': build.version.baseOS,
      'board': build.board,
      'bootloader': build.bootloader,
      'brand': build.brand,
      'device': build.device,
      'display': build.display,
      'fingerprint': build.fingerprint,
      'hardware': build.hardware,
      'host': build.host,
      'id': build.id,
      'manufacturer': build.manufacturer,
      'model': build.model,
      'product': build.product,
      'supported32BitAbis': build.supported32BitAbis,
      'supported64BitAbis': build.supported64BitAbis,
      'supportedAbis': build.supportedAbis,
      'tags': build.tags,
      'type': build.type,
      'isPhysicalDevice': build.isPhysicalDevice,
      'systemFeatures': build.systemFeatures,
      'serialNumber': build.serialNumber,
    };
  }
  if (Platform.isIOS) {
    // iOS 设备
    IosDeviceInfo build = await deviceInfo.iosInfo;
    info = <String, dynamic>{
      'name': build.name,
      'systemName': build.systemName,
      'systemVersion': build.systemVersion,
      'model': build.model,
      'localizedModel': build.localizedModel,
      'identifierForVendor': build.identifierForVendor,
      'isPhysicalDevice': build.isPhysicalDevice,
      'utsname.sysname:': build.utsname.sysname,
      'utsname.nodename:': build.utsname.nodename,
      'utsname.release:': build.utsname.release,
      'utsname.version:': build.utsname.version,
      'utsname.machine:': build.utsname.machine,
      'brand': build.name,
      'system': build.systemVersion,
      'serial': build.systemName,
    };
  }
  final Map<String, dynamic> reportData = {
    'error': error.toString(),
    'stack_trace': stackTrace?.toString(),
    'device_info': info,
    'timestamp': DateTime.now().toIso8601String(),
    'userId': '',
    'username': userModel != null ? userModel.nickname : '',
    'brand': info['brand'],
    'serial': info['serial'],
    'system': info['system'],
  };
  try {
    EcyRequestbasemanager().post("/app/api/app/commons/crash", reportData);
  } catch (e) {
    print('Error sending report: $e');
  }
}

class MyApp extends StatefulWidget {
  final GlobalKey<NavigatorState> gnavigatorKey;

  MyApp({required this.gnavigatorKey});
  // This widget is the root of your application.

  @override
  State<StatefulWidget> createState() {
    return _MyAppState(this.gnavigatorKey);
  }
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  _MyAppState(this.navigatorKey);
  final GlobalKey<NavigatorState> navigatorKey;
  final JPush jpush = new JPush();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    initPlatformState();
    EcyQQUtil.init();
    EcyWxUtil().init();
    EcyPermission.requestPermissions();
    FlutterEasyPermission().addPermissionCallback(
      onGranted: (requestCode, perms, perm) {
        EcyLogger.error("android获得授权:$perms");
        EcyLogger.error("iOS获得授权:$perm");
        EcyEventBus().emit(EcyEventConst.kHttpConnected);
      },
      onDenied: (requestCode, perms, perm, isPermanent) {
        if (isPermanent) {
          FlutterEasyPermission.showAppSettingsDialog(title: "Camera");
        } else {
          EcyLogger.error("android授权失败:$perms");
          EcyLogger.error("iOS授权失败:$perm");
        }
      },
      onSettingsReturned: () {
      EcyEventBus().emit(EcyEventConst.kHttpConnected);
      FlutterEasyPermission.has(
              perms: [], permsGroup: EcyPermission.permissionGroup)
          .then((value) => value
              ? EcyLogger.error("已获得授权:$EcyPermission.permissionGroup]")
              : EcyLogger.error("未获得授权:$EcyPermission.permissionGroup"));
      }
    );
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.resumed:
        // APP 恢复到前台
        print('APP resumed - 发送恢复事件');
        jpush.setBadge(0);
        EcyEventBus().emit(EcyEventConst.kAppResumed);
        break;
      case AppLifecycleState.inactive:
        // APP 即将进入后台
        print('APP inactive - 发送暂停事件');
        EcyEventBus().emit(EcyEventConst.kAppInactive);
        break;
      case AppLifecycleState.paused:
        // APP 进入后台
        print('APP paused - 发送暂停事件');
        EcyEventBus().emit(EcyEventConst.kAppPaused);
        break;
      case AppLifecycleState.detached:
        // APP 被终止
        print('APP detached - 发送终止事件');
        EcyEventBus().emit(EcyEventConst.kAppDetached);
        break;
      default:
        break;
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(375, 812),
      builder: (context, child) {
        return MaterialApp(
          navigatorKey: navigatorKey,
          title: '有谷气',
          theme: ThemeData(
            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            useMaterial3: true,
          ),
          // home: ContainPage(key: Key("home")),
          builder: EasyLoading.init(),
          initialRoute: '/',
          // 渲染路由
          onGenerateRoute: EcyRouter().onGenerateRoute,
          localizationsDelegates: const [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          supportedLocales: const [Locale("zh", "CH"), Locale("en", "US")],
          locale: const Locale('zh', 'CN'),
        );
      },
    );
  }

// Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    try {
      jpush.addEventHandler(
          onReceiveNotification: (Map<String, dynamic> message) async {
        EcyLogger.log("flutter onReceiveNotification: $message");
      }, onOpenNotification: (Map<String, dynamic> message) async {
        jpush.setBadge(0);
        EcyLogger.log("flutter onOpenNotification: $message");
      }, onReceiveMessage: (Map<String, dynamic> message) async {
        EcyLogger.log("flutter onReceiveMessage: $message");
      }, onReceiveNotificationAuthorization:
              (Map<String, dynamic> message) async {
        EcyLogger.log("flutter onReceiveNotificationAuthorization: $message");
      }, onNotifyMessageUnShow: (Map<String, dynamic> message) async {
        EcyLogger.log("flutter onNotifyMessageUnShow: $message");
      }, onInAppMessageShow: (Map<String, dynamic> message) async {
        EcyLogger.log("flutter onInAppMessageShow: $message");
      }, onCommandResult: (Map<String, dynamic> message) async {
        EcyLogger.log("flutter onCommandResult: $message");
      }, onInAppMessageClick: (Map<String, dynamic> message) async {
        EcyLogger.log("flutter onInAppMessageClick: $message");
      }, onConnected: (Map<String, dynamic> message) async {
        EcyLogger.log("flutter onConnected: $message");
      });
    } on PlatformException {
      EcyLogger.log('Failed to get platform version.');
    }

    jpush.setAuth(enable: true);
    jpush.setup(
      appKey: "b733eb713490d66f2ab1b6ac", //你自己应用的 AppKey
      channel: "theChannel",
      production: !debug,
      debug: true,
    );

    jpush.setBadge(0);

    jpush.applyPushAuthority(
        new NotificationSettingsIOS(sound: true, alert: true, badge: true));

    // Platform messages may fail, so we use a try/catch PlatformException.
    jpush.getRegistrationID().then((rid) {
      if (rid.length > 0) {
        EcyEventBus().emit(EcyEventConst.kHttpConnected);
      }
      EcyLogger.log("flutter get registration id : $rid");
    });

    // iOS要是使用应用内消息，请在页面进入离开的时候配置pageEnterTo 和  pageLeave 函数，参数为页面名。
    // jpush.pageEnterTo("HomePage"); // 在离开页面的时候请调用 jpush.pageLeave("HomePage");

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
  }
}
